package com.javasm.crm.service.aftersale.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasm.crm.domin.criteria.aftesale.RefacInApplyCriteria;
import com.javasm.crm.domin.entity.aftersale.RefacInApply;
import com.javasm.crm.domin.entity.aftersale.RefacInGoods;
import com.javasm.crm.domin.entity.aftersale.RefacOutApply;
import com.javasm.crm.domin.entity.base.BaseEntity;
import com.javasm.crm.domin.vo.aftersale.RefacInApplyVO;
import com.javasm.crm.mapper.aftersale.RefacInApplyMapper;
import com.javasm.crm.service.aftersale.IInorderService;
import com.javasm.crm.service.aftersale.IRefacInApplyService;
import com.javasm.crm.service.aftersale.IRefacInGoodsService;
import com.javasm.crm.service.aftersale.IRefacOutApplyService;
import com.javasm.crm.utils.transfer.OutGoodToInGoodTransfer;
import com.javasm.crm.utils.transfer.RefacInApplyTransfer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lirui
 * @since 2021-07-11
 */
@Service
@Transactional
public class RefacInApplyServiceImpl extends ServiceImpl<RefacInApplyMapper, RefacInApply> implements IRefacInApplyService {

    @Resource
    private RefacInApplyTransfer transfer;

    @Resource
    private IRefacInGoodsService inGoodsService;

    @Resource
    private IRefacOutApplyService outApplyService;

    @Resource
    private IInorderService inorderService;

    @Override
    public Page<RefacInApply> getPage(RefacInApplyCriteria criteria) {
        //分页信息
        Integer currentPage = criteria.getCurrentPage();
        Integer pageSize = criteria.getPageSize();

        //条件查询构造器
        QueryWrapper<RefacInApply> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<RefacInApply> lambda = wrapper.lambda();

        //创建起止时间
        LocalDateTime startTime = criteria.getStartTime();
        LocalDateTime endTime = criteria.getEndTime();

        if (startTime != null && endTime != null) {
            lambda.between(RefacInApply::getCreateTime, startTime, endTime);
        }

        //审批起止时间
        LocalDateTime appStartTime = criteria.getAppStartTime();
        LocalDateTime appEndTime = criteria.getAppEndTime();

        if (appStartTime != null && appEndTime != null) {
            lambda.between(RefacInApply::getApproverTime, appStartTime, appEndTime);
        }

        //返厂出库单号
        String odoCode = criteria.getIdoCode();
        if (odoCode != null && !"".equals(odoCode)) {
            lambda.like(RefacInApply::getOdoCode, odoCode);
        }

        //返厂出库标志
        Integer status = criteria.getStatus();
        if (status != null) {
            lambda.eq(RefacInApply::getStatus, status);
        }

        //审核状态
        Integer approveStatus = criteria.getApproveStatus();
        if (approveStatus != null) {
            lambda.eq(RefacInApply::getApproveStatus, approveStatus);
        }

        //审核人
        String approver = criteria.getApprover();
        if (approver != null && !"".equals(approver)) {
            lambda.like(RefacInApply::getApprover, approver);
        }

        //制单人
        String createBy = criteria.getCreateBy();
        if (createBy != null && !"".equals(createBy)) {
            lambda.like(RefacInApply::getCreateBy, createBy);
        }

        lambda.orderByAsc(RefacInApply::getApproveStatus);

        //分页查询
        Page<RefacInApply> page = new Page<>(currentPage, pageSize);

        page(page, wrapper);

        return page;
    }

    @Override
    public boolean addInApply(RefacInApplyVO refacInApplyVO, String userName) {

        List<RefacInGoods> refacInGoods = refacInApplyVO.getRefacInGoods();

        RefacInApply refacInApply = transfer.toEntity(refacInApplyVO);

        //保存入库申请单
        boolean save = save(refacInApply);

        if (!save) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        //更新入库申请单，创建时间、code等
        UpdateWrapper<RefacInApply> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<RefacInApply> lambda = updateWrapper.lambda();

        Long id = refacInApply.getId();
        String idoCode = UUID.randomUUID().toString().substring(0, 5) + id;

        lambda.set(RefacInApply::getIdoCode, idoCode)
                .set(RefacInApply::getCreateBy, userName)
                .set(BaseEntity::getCreateTime, LocalDateTime.now())
                .set(RefacInApply::getApproveStatus, 1);//1，未审核

        boolean update = update(updateWrapper);

//        if (!update) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }

        //更新入库申请单商品
        if (refacInGoods.size() > 0) {

            for (RefacInGoods refacInGood : refacInGoods) {
                refacInGood.setIdoCode(idoCode);
                refacInGood.setIdoId(Integer.valueOf(id.toString()));
            }

            boolean saveBatch = inGoodsService.saveBatch(refacInGoods);
            if (!saveBatch) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }

        //更新对应的出库申请单状态 status = 2 （待入库），避免被继续查询到
        Integer odoId = refacInApplyVO.getOdoId();
        UpdateWrapper<RefacOutApply> outApplyUpdateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<RefacOutApply> outApplyLambdaUpdateWrapper = outApplyUpdateWrapper.lambda();

        outApplyLambdaUpdateWrapper.eq(BaseEntity::getId, odoId)
                .set(RefacOutApply::getStatus, 2);

        boolean outApplyUpdate = outApplyService.update(outApplyUpdateWrapper);

//        if (!outApplyUpdate) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }

        return true;
    }

    @Override
    public boolean alterInApply(RefacInApplyVO refacInApplyVO, String userName) {

        List<RefacInGoods> refacInGoods = refacInApplyVO.getRefacInGoods();

        UpdateWrapper<RefacInApply> wrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<RefacInApply> lambda = wrapper.lambda();

        lambda.set(RefacInApply::getComments, refacInApplyVO.getComments());

        boolean update = update(wrapper);

//        if (!update) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }

        boolean batchById = inGoodsService.updateBatchById(refacInGoods);


//        if (!batchById) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }

        return true;
    }

    @Override
    public boolean batchDelete(List<Serializable> idList) {

        //修改对应的出库申请单状态 status=2 （待入库） ==> status=1（已出库）
        QueryWrapper<RefacInApply> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<RefacInApply> lambda = wrapper.lambda();

        lambda.select(RefacInApply::getOdoId).in(BaseEntity::getId, idList);

        List<Object> odoIdList = listObjs(wrapper);//获取对应的出库单id集合

        UpdateWrapper<RefacOutApply> updateWrapper = new UpdateWrapper<>();
        LambdaUpdateWrapper<RefacOutApply> outApplyLambdaUpdateWrapper = updateWrapper.lambda();

        outApplyLambdaUpdateWrapper
                .in(BaseEntity::getId, odoIdList)
                .set(RefacOutApply::getStatus, 1);

        boolean update = outApplyService.update(outApplyLambdaUpdateWrapper);

        if (!update) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        //删除对应的入库单商品
        QueryWrapper<RefacInGoods> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<RefacInGoods> inGoodsLambdaQueryWrapper = queryWrapper.lambda();

        inGoodsLambdaQueryWrapper.in(RefacInGoods::getIdoId, idList);

        boolean remove = inGoodsService.remove(inGoodsLambdaQueryWrapper);

        if (!remove) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        //删除入库申请单
        boolean removeByIds = removeByIds(idList);

        if (!removeByIds) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        return true;
    }

    @Override
    public boolean approveApply(RefacInApply refacInApply, String userName) {

        //更新入库申请单，更新审批信息及状态信息
        UpdateWrapper<RefacInApply> refacInApplyUpdateWrapper = new UpdateWrapper<>();

        LambdaUpdateWrapper<RefacInApply> inApplyLambdaUpdateWrapper = refacInApplyUpdateWrapper.lambda();

        Long id = refacInApply.getId();
        Integer approveStatus = refacInApply.getApproveStatus();
        String approverComments = refacInApply.getApproverComments();
        LocalDateTime now = LocalDateTime.now();

        inApplyLambdaUpdateWrapper.eq(BaseEntity::getId, id)
                .set(RefacInApply::getApproveStatus, approveStatus)
                .set(RefacInApply::getApproverComments, approverComments)
                .set(RefacInApply::getApproverTime, now)
                .set(RefacInApply::getApprover, userName);

        boolean update = update(refacInApplyUpdateWrapper);

        if (!update) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

        //审核通过，调用生成入库订单方法，生成入库订单，
        if (approveStatus == 2) {
            boolean newInOrder = inorderService.generateInOutOrder(refacInApply);

            if (!newInOrder) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }

//        //更改对应出库订单的状态status = 3， 已入库（入库订单审核时完成）
//        Integer odoId = refacInApply.getOdoId();
//        UpdateWrapper<RefacOutApply> outApplyUpdateWrapper = new UpdateWrapper<>();
//        LambdaUpdateWrapper<RefacOutApply> lambda = outApplyUpdateWrapper.lambda();
//
//        lambda.eq(BaseEntity::getId, odoId).set(RefacOutApply::getStatus, 3);
//
//        boolean outApplyUpdate = outApplyService.update(outApplyUpdateWrapper);
//
//        if (!outApplyUpdate) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }

        return true;
    }
}
